package com.mostromas.ess.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mostromas.ess.entities.Fabric;
import com.mostromas.ess.entities.FabricComposition;
import com.mostromas.ess.product.mapper.FabricMapper;
import com.mostromas.ess.product.req.FabricREQ;
import com.mostromas.ess.product.service.IFabricCompositionService;
import com.mostromas.ess.product.service.IFabricService;
import com.mostromas.ess.util.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class FabricServiceImpl extends ServiceImpl<FabricMapper, Fabric> implements IFabricService {

    @Autowired
    private IFabricCompositionService fabricCompositionService;

    @Override
    public Result queryPage(FabricREQ req) {
        IPage<Fabric> fabricDetails = baseMapper.findFabricDetails(req.getPage(), req);

        return Result.ok(fabricDetails);
    }

    @Transactional
    @Override
    public Result saveFabricComposition(Fabric entity, List<FabricComposition> compositionList) {
        super.save(entity);
        baseMapper.saveFabricComposition(entity.getId(),compositionList);
        return Result.ok();
    }

    @Override
    public Result findDetailsById(String fabricId) {

        return Result.ok(baseMapper.findDetailsById(fabricId));
    }

    @Transactional
    @Override
    public Result updateDetails(Fabric entity, List<FabricComposition> compositionList) {
        QueryWrapper<FabricComposition> wrapper = new QueryWrapper<>();
        wrapper.eq("fabric_id",entity.getId());
        boolean remove = fabricCompositionService.remove(wrapper);
        super.updateById(entity);
        boolean b = baseMapper.saveFabricComposition(entity.getId(), compositionList);
        return Result.ok();
    }

    @Override
    public Result findDetailsByProductId(String productId) {
        List<Fabric> fabricList = baseMapper.findDetailsByProductId(productId);
        return Result.ok(fabricList);
    }

    @Transactional
    @Override
    public boolean removeById(Serializable id) {
        super.removeById(id);
        QueryWrapper<FabricComposition> wrapper = new QueryWrapper<>();
        wrapper.eq("fabric_id",id);
        boolean remove = fabricCompositionService.remove(wrapper);
        return false;
    }
}
